<template>
  <div class="post-detail">
    <div v-if="post" class="post-container">
      <div class="post-header">
        <img :src="getCoverUrl(post?.coverImage)" :alt="post?.title" @error="onImgError" />
        <h1>{{ post.title }}</h1>
        <div class="post-meta">
          <span class="post-date">{{ formatDate(post.createdAt) }}</span>
          <span class="post-category">{{ post.category }}</span>
          <span v-if="post.readTime" class="post-read-time">{{ post.readTime }} 分钟阅读</span>
        </div>
      </div>
      <div class="post-content" v-html="post.content"></div>
      
      <!-- 评论区域 -->
      <div class="comments-section">
        <h3>评论 ({{ comments.length }})</h3>
        <div class="comment-form">
          <textarea v-model="newComment" placeholder="写下你的评论..." />
          <button @click="handleSubmitComment" :disabled="submitting">发表评论</button>
        </div>
        <div class="comments-list">
          <div v-for="comment in comments" :key="comment.id" class="comment">
            <div class="comment-header">
              <span class="comment-author">{{ comment.author }}</span>
              <span class="comment-date">{{ formatDate(comment.createdAt) }}</span>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
          </div>
        </div>
      </div>
    </div>
    <div v-else class="error">
      <h2>文章未找到</h2>
      <p>抱歉，您访问的文章不存在或已被删除。</p>
      <router-link to="/" class="btn btn-primary">返回文章列表</router-link>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import type { Article, Comment } from './types'
import { fetchArticle, fetchComments as fetchCommentsService, submitComment as submitCommentService, getCoverUrl, onImgError } from './service'

const route = useRoute()
const post = ref<Article | null>(null)
const comments = ref<Comment[]>([])
const newComment = ref('')
const submitting = ref(false)

const formatDate = (dateString: string | undefined): string => {
  if (!dateString) return '未知日期'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

const fetchPost = async () => {
  try {
    post.value = await fetchArticle(route.params.id as string)
    await loadComments()
  } catch (error) {
    console.error('获取文章失败:', error)
  }
}

const loadComments = async () => {
  if (!post.value) return
  try {
    comments.value = await fetchCommentsService(post.value.id)
  } catch (error) {
    console.error('获取评论失败:', error)
  }
}

const handleSubmitComment = async () => {
  if (!newComment.value.trim() || !post.value) return
  
  try {
    submitting.value = true
    await submitCommentService(post.value.id, newComment.value)
    newComment.value = ''
    await loadComments()
  } catch (error) {
    alert('评论失败：' + (error instanceof Error ? error.message : '未知错误'))
  } finally {
    submitting.value = false
  }
}

onMounted(fetchPost)
</script>

<style scoped>
@import './style.css';
</style> 